import 'dart:async';
import 'package:flutter/material.dart';
import 'package:hxdj/common/components/my_text.dart';
import 'package:hxdj/common/my_header_global.dart';

/*
* 交易倒计时
* */
class OrderCountDown extends StatefulWidget {
  //剩余时间

  final int remainingTime;
  final Function() callback;
  const OrderCountDown({super.key, required this.remainingTime, required this.callback});
  @override
  State<StatefulWidget> createState() {
    return _OrderCountDownState();
  }
}

class _OrderCountDownState extends State<OrderCountDown> {
  late Timer timer;

  String remainingTimeStr = "";
  @override
  void initState() {
    super.initState();
    //开启定时器
    starTimer();
  }

  @override
  Widget build(BuildContext context) {
    return MyText("剩余支付时间：$remainingTimeStr", color: MyColours.colorFF4414, fontSize: 13);
  }

  starTimer() {
    int remainingTime = widget.remainingTime;
    // int day;
    int hour;
    int minute;
    int seconds;
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      remainingTime -= 1;

      debugPrint("remainingTime:$remainingTime");

      // day = remainingTime ~/ 3600 ~/ 24;
      hour = remainingTime ~/ 3600 % 24;
      minute = remainingTime % 3600 ~/ 60;
      seconds = remainingTime % 60;

      if (remainingTime < 0) {
        widget.callback();
        timer.cancel();
        return;
      }
      remainingTimeStr = "${completeTime(hour)}:${completeTime(minute)}:${completeTime(seconds)}";

      setState(() {});
    });
  }

  @override
  void dispose() {
    super.dispose();
    timer.cancel();
  }

  String completeTime(int time) {
    if (time < 0) {
      return "00";
    }
    if (time < 10) {
      return "0$time";
    }

    return time.toString();
  }
}
